package cn.kwq.project_manger.dtoUtils;

import cn.kwq.project_manger.chat.QChatMsg;
import cn.kwq.project_manger.pojo.QUser;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/02/23/14:19
 * @Description:
 */
@Data
@Component
@Slf4j
public class ChatUtils {

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    public String getLastMsg(Long from, Long to) {
        QChatMsg cs=QChatMsg.chatMsg;
        return   jpaQueryFactory.select(cs.msg).from(cs)
                .where((cs.fromId.eq(from).and(cs.toId.eq(to)))
                        .or(cs.fromId.eq(to).and(cs.toId.eq(from))))
                .orderBy(cs._super.createdDate.asc())
                .fetchFirst();
    }

    public String getUserNameByFromId(Long fromId, Long toId, Long from) {
        QUser user=QUser.user;
        String userName=null;
        if (fromId.equals(from)){
            userName = jpaQueryFactory.select(user.userName)
                    .from(user)
                    .where(user.id.eq(toId))
                    .fetchFirst();
        }
        if (toId.equals(from)){
            userName = jpaQueryFactory.select(user.userName)
                    .from(user)
                    .where(user.id.eq(fromId))
                    .fetchFirst();
        }
        return userName;
    }
}
